package tushare

import (
	"tushare/model/mysql"
)

type NowAngle struct {
	Id       int64   `json:"id"`
	TsCode   string  `json:"ts_code"`
	Angle    float64 `json:"angle"`
	ImAmount float64 `json:"im_amount"`
}

type NowAngleJoinStock struct {
	Id       int64   `json:"id"`
	TsCode   string  `json:"ts_code"`
	Angle    float64 `json:"angle"`
	ImAmount float64 `json:"im_amount"`
	Close    float64 `json:"close"`
}

func NowAngleCreate(na NowAngle) {
	mysql.DB.Table("tushare_now_angle").Create(&na)
}

func NowAngleByTsCode(tsCode string) NowAngle {
	na := NowAngle{}
	mysql.DB.Table("tushare_now_angle").Where("ts_code = ?", tsCode).First(&na)
	return na
}

func NowAngleUpdate(na NowAngle) {
	mysql.DB.Table("tushare_now_angle").Save(&na)
}

func NowAngleList(page, pageSize int64, angle, imAmount, close float64) []NowAngleJoinStock {
	page = page
	pageSize = pageSize
	offset := (page - 1) * pageSize

	na := []NowAngleJoinStock{}
	mysql.DB.Table("tushare_now_angle").Select(`
	tushare_now_angle.ts_code as ts_code,
	tushare_now_angle.angle as angle,
	tushare_now_angle.im_amount as im_amount,
	tushare_stock.close as close
	`).Joins(`
	LEFT JOIN tushare_stock ON tushare_now_angle.ts_code = tushare_stock.ts_code
	`).Where(`
	tushare_now_angle.angle >= ?
AND tushare_now_angle.im_amount > ?
AND tushare_stock.close <= ?
AND tushare_stock.name NOT LIKE '%ST%'
	`, angle, imAmount, close).Order(`
	tushare_now_angle.angle DESC
	`).Limit(pageSize).Offset(offset).Scan(&na)
	return na
}

func NowAngleCount(angle, imAmount, close float64) int64 {
	var count int64

	mysql.DB.Table("tushare_now_angle").Select(`
	tushare_now_angle.id as id,
	`).Joins(`
	LEFT JOIN tushare_stock ON tushare_now_angle.ts_code = tushare_stock.ts_code
	`).Where(`
	tushare_now_angle.angle >= ?
AND tushare_now_angle.im_amount > ?
AND tushare_stock.close <= ?
AND tushare_stock.name NOT LIKE '%ST%'
	`, angle, imAmount, close).Order(`
	tushare_now_angle.angle DESC
	`).Count(&count)
	return count
}
